from rest_framework import generics, status, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django.db import transaction
from django.core.exceptions import ValidationError
from .models import Deck, DeckCard
from .serializers import (
    DeckSerializer, DeckCardAddSerializer, DeckCreateSerializer, 
    DeckValidationSerializer, DeckCardSerializer
)


class DeckListView(generics.ListCreateAPIView):
    """卡组列表和创建"""
    permission_classes = [permissions.IsAuthenticated]
    
    def get_serializer_class(self):
        if self.request.method == 'POST':
            return DeckCreateSerializer
        return DeckSerializer
    
    def get_queryset(self):
        return Deck.objects.filter(user=self.request.user, is_active=True)
    
    def perform_create(self, serializer):
        serializer.save(user=self.request.user)


class DeckDetailView(generics.RetrieveUpdateDestroyAPIView):
    """卡组详情、更新和删除"""
    serializer_class = DeckSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return Deck.objects.filter(user=self.request.user)


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def add_card_to_deck(request, deck_id):
    """向卡组添加卡牌"""
    try:
        deck = Deck.objects.get(id=deck_id, user=request.user)
    except Deck.DoesNotExist:
        return Response({'error': '卡组不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    serializer = DeckCardAddSerializer(data=request.data, context={'request': request})
    if serializer.is_valid():
        card_id = serializer.validated_data['card_id']
        quantity = serializer.validated_data['quantity']
        
        # 检查卡组是否已满
        if deck.total_cards + quantity > 5:
            return Response({'error': '卡组最多只能包含5张卡牌'}, status=status.HTTP_400_BAD_REQUEST)
        
        # 检查是否已经存在该卡牌
        existing_deck_card = DeckCard.objects.filter(deck=deck, card_id=card_id).first()
        if existing_deck_card:
            return Response({'error': '卡组中已存在该卡牌'}, status=status.HTTP_400_BAD_REQUEST)
        
        # 检查5星卡牌限制
        from apps.cards.models import Card
        card = Card.objects.get(id=card_id)
        if card.star_level == 5:
            five_star_count = sum(dc.quantity for dc in deck.deck_cards.all() if dc.card.star_level == 5)
            if five_star_count >= 1:
                return Response({'error': '卡组最多只能包含1张5星卡牌'}, status=status.HTTP_400_BAD_REQUEST)
        
        with transaction.atomic():
            DeckCard.objects.create(
                deck=deck,
                card_id=card_id,
                quantity=quantity
            )
        
        # 返回更新后的卡组信息
        deck_serializer = DeckSerializer(deck)
        return Response({
            'message': '卡牌添加成功',
            'deck': deck_serializer.data
        })
    
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['DELETE'])
@permission_classes([permissions.IsAuthenticated])
def remove_card_from_deck(request, deck_id, card_id):
    """从卡组移除卡牌"""
    try:
        deck = Deck.objects.get(id=deck_id, user=request.user)
        deck_card = DeckCard.objects.get(deck=deck, card_id=card_id)
    except Deck.DoesNotExist:
        return Response({'error': '卡组不存在'}, status=status.HTTP_404_NOT_FOUND)
    except DeckCard.DoesNotExist:
        return Response({'error': '卡牌不在卡组中'}, status=status.HTTP_404_NOT_FOUND)
    
    deck_card.delete()
    
    # 返回更新后的卡组信息
    deck_serializer = DeckSerializer(deck)
    return Response({
        'message': '卡牌移除成功',
        'deck': deck_serializer.data
    })


@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def get_user_cards(request):
    """获取用户拥有的卡牌列表"""
    from apps.cards.models import UserCard
    from apps.cards.serializers import CardSerializer
    
    user_cards = UserCard.objects.filter(user=request.user).select_related('card')
    cards_data = []
    
    for user_card in user_cards:
        card_data = CardSerializer(user_card.card).data
        card_data['user_quantity'] = user_card.quantity
        cards_data.append(card_data)
    
    return Response(cards_data)


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def validate_deck(request, deck_id):
    """验证卡组是否符合规则"""
    try:
        deck = Deck.objects.get(id=deck_id, user=request.user)
    except Deck.DoesNotExist:
        return Response({'error': '卡组不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    is_valid = deck.is_valid
    validation_errors = deck.validation_errors
    
    return Response({
        'is_valid': is_valid,
        'validation_errors': validation_errors,
        'total_cards': deck.total_cards
    })


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def duplicate_deck(request, deck_id):
    """复制卡组"""
    try:
        original_deck = Deck.objects.get(id=deck_id, user=request.user)
    except Deck.DoesNotExist:
        return Response({'error': '原卡组不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    # 检查用户卡组数量限制
    user_deck_count = Deck.objects.filter(user=request.user, is_active=True).count()
    if user_deck_count >= 10:
        return Response({'error': '每个用户最多只能拥有10个卡组'}, status=status.HTTP_400_BAD_REQUEST)
    
    new_name = f"{original_deck.name} (副本)"
    counter = 1
    while Deck.objects.filter(user=request.user, name=new_name, is_active=True).exists():
        new_name = f"{original_deck.name} (副本{counter})"
        counter += 1
    
    with transaction.atomic():
        new_deck = Deck.objects.create(
            user=request.user,
            name=new_name
        )
        
        # 复制卡组中的卡牌
        for deck_card in original_deck.deck_cards.all():
            DeckCard.objects.create(
                deck=new_deck,
                card=deck_card.card,
                quantity=deck_card.quantity
            )
    
    deck_serializer = DeckSerializer(new_deck)
    return Response({
        'message': '卡组复制成功',
        'deck': deck_serializer.data
    })
